package com.ruoyi.quartz.task;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.supplier.domain.TbCheckProductDetail;
import com.ruoyi.supplier.domain.TbPrice;
import com.ruoyi.supplier.mapper.TbPriceMapper;
import com.ruoyi.supplier.service.ITbCheckProductDetailService;
import com.ruoyi.supplier.service.ITbPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Component("elecTask")
public class ElecTask {


    @Autowired
    public TbPriceMapper tbPriceMapper;

    @Autowired
    public ITbCheckProductDetailService iTbCheckProductDetailService;

    /**
     * 设置参考单价，根据验货单最低价格，进行设置
     */
    public void referencePriceTask()
    {
        List<TbCheckProductDetail> tbCheckProductDetails = iTbCheckProductDetailService.selectTbCheckProductDetaiMinPrice();
        List<TbPrice> tbPrices = tbPriceMapper.selectTbPrice();
        if(tbCheckProductDetails !=null && tbCheckProductDetails.size()>0){
            tbCheckProductDetails.forEach(tbCheckProductDetail -> {

                TbPrice tbPrice=new TbPrice();
                tbPrice.setPriceId(tbCheckProductDetail.getPriceId());
                /**
                 * 设置参考单价
                 */
                tbPrice.setReferencePrice(tbCheckProductDetail.getPrice());
                tbPrice.setUpdateTime(DateUtils.getNowDate());
                tbPrice.setUpdateBy(UserConstants.SYS_USER);
                /**
                 * 防止重复设置参考单价，如果商品价格表中的参考单价，没有变化，不进行设置
                 * 如果商品价格表的参考单价等于验货单中的进货价格，则不进行更新
                 * 如果商品价格表的参考单价大于验货单中的进货价格，则进行更新
                 */
                tbPrices.forEach(tbPrice1 -> {
                   if( tbPrice1.getPriceId().equals(tbPrice.getPriceId())){
                      if(!tbPrice1.getReferencePrice().equals(tbPrice.getReferencePrice())){
                          if(tbPrice.getReferencePrice().compareTo(tbPrice1.getReferencePrice())==-1 || tbPrice1.getReferencePrice().compareTo(BigDecimal.ZERO)==0){
                              tbPriceMapper.updateTbPrice(tbPrice);
                          }
                      }
                   }
                });
            });
        }

    }
}
